/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.kj.member.web;

import com.jeesite.common.codec.EncodeUtils;
import com.jeesite.common.collect.ListUtils;
import com.jeesite.common.collect.MapUtils;
import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Extend;
import com.jeesite.common.entity.Page;
import com.jeesite.common.lang.DateUtils;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.mapper.JsonMapper;
import com.jeesite.common.utils.excel.ExcelExport;
import com.jeesite.common.utils.excel.annotation.ExcelField.Type;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.kj.user.service.UserExtendService;
import com.jeesite.modules.sys.entity.EmpUser;
import com.jeesite.modules.sys.entity.Role;
import com.jeesite.modules.sys.entity.User;
import com.jeesite.modules.sys.entity.UserDataScope;
import com.jeesite.modules.sys.service.RoleService;
import com.jeesite.modules.sys.service.UserService;
import com.jeesite.modules.sys.utils.UserUtils;
import com.jeesite.modules.kj.member.entity.Member;
import com.jeesite.modules.kj.member.entity.MemberUser;
import com.jeesite.modules.kj.member.service.MemberService;
import com.jeesite.modules.kj.member.service.MemberUserService;
import com.jeesite.modules.kj.member.utils.MemberUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 会员用户Controller
 * @author ThinkGem
 * @version 2017-03-26
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/memberUser")
public class MemberUserController extends BaseController {

	@Autowired
	private MemberUserService memberUserService;
	@Autowired
	private MemberService memberService;
	@Autowired
	private UserService userService;

	@Autowired
	private UserExtendService userExtendService;
	@Autowired
	private RoleService roleService;

	@ModelAttribute
	public MemberUser get(String userCode, boolean isNewRecord) {
		return memberUserService.get(userCode, isNewRecord);
	}

	@RequiresPermissions("sys:memberUser:view")
	@RequestMapping(value = "index")
	public String index(MemberUser memberUser, Model model) {
		return "modules/kj/member/memberUserIndex";
	}
	
	@RequiresPermissions("sys:memberUser:view")
	@RequestMapping(value = "list")
	public String list(MemberUser memberUser, Model model) {
		return "modules/kj/member/memberUserList";
	}

	@RequiresPermissions("user")
	@RequestMapping(value = "listData")
	@ResponseBody
	public Page<MemberUser> listData(MemberUser memberUser, Boolean isAll, String ctrlPermi, HttpServletRequest request, HttpServletResponse response) {
		memberUser.getMember().getOffice().setIsQueryChildren(true);
		memberUser.getMember().getCompany().setIsQueryChildren(true);
		if (!(isAll != null && isAll) || Global.isStrictMode()){
			memberUserService.addDataScopeFilter(memberUser, ctrlPermi);
		}
		memberUser.setPage(new Page<>(request, response));
		Page<MemberUser> page = memberUserService.findPage(memberUser);
		return page;
	}

	@RequiresPermissions("sys:memberUser:view")
	@RequestMapping(value = "form")
	public String form(MemberUser memberUser, String op, Model model) {
		
		Member member = memberUser.getMember();
		
		// 设置默认的部门
		if (StringUtils.isBlank(member.getCompany().getCompanyCode())) {
			member.setCompany(MemberUtils.getCompany());
		}
		
		// 设置默认的公司
		if (StringUtils.isBlank(member.getOffice().getOfficeCode())) {
			member.setOffice(MemberUtils.getOffice());
		}

		
		// 获取当前编辑用户的角色和权限
		if (StringUtils.inString(op, Global.OP_AUTH)) {
			// 获取当前用户所拥有的角色
			Role role = new Role();
			role.setUserCode(memberUser.getUserCode());
			model.addAttribute("roleList", roleService.findListByUserCode(role));
		}
		// 操作类型：add: 全部； edit: 编辑； auth: 授权
		model.addAttribute("op", op);
		model.addAttribute("memberUser", memberUser);


		return "modules/kj/member/memberUserForm";
	}


	@RequiresPermissions(value={"sys:memberUser:edit"})
	@RequestMapping({"checkLoginCode"})
	@ResponseBody
	public String checkLoginCode(String oldLoginCode, MemberUser memberUser) {
		return userExtendService.checkMemberLoginCode(oldLoginCode, memberUser.getExtend().getExtendS1());
	}
	@RequiresPermissions(value={"sys:memberUser:edit"})
	@RequestMapping({"checkMobile"})
	@ResponseBody
	public String checkMobile(String oldLoginCode, MemberUser memberUser) {
		return userExtendService.checkMemberMobile(oldLoginCode, memberUser.getMobile());
	}
	@RequiresPermissions(value={"sys:memberUser:edit"})
	@RequestMapping({"checkEmail"})
	@ResponseBody
	public String checkEmail(String oldLoginCode, MemberUser memberUser) {
		return userExtendService.checkMemberEmail(oldLoginCode, memberUser.getEmail());
	}

	@RequiresPermissions(value={"sys:memberUser:edit","sys:memberUser:authRole"}, logical=Logical.OR)
	@PostMapping(value = "save")
	@ResponseBody
	public String save(@Validated MemberUser memberUser, String oldLoginCode, String op, HttpServletRequest request) {
		if (User.isSuperAdmin(memberUser.getUserCode())) {
			return renderResult(Global.FALSE, "非法操作，不能够操作此用户！");
		}
		if (!MemberUser.USER_TYPE_MEMBER.equals(memberUser.getUserType())){
			return renderResult(Global.FALSE, "非法操作，不能够操作此用户！");
		}
		if (!Global.TRUE.equals(userExtendService.checkMemberLoginCode(oldLoginCode, memberUser.getExtend().getExtendS1()/*, null*/))) {
			return renderResult(Global.FALSE, text("保存用户失败，登录账号''{0}''已存在", memberUser.getExtend().getExtendS1()));
		}

		if (!Global.TRUE.equals(userExtendService.checkMemberMobile(oldLoginCode, memberUser.getMobile()/*, null*/))) {
			return renderResult(Global.FALSE, text("保存用户失败，登录手机号''{0}''已存在", memberUser.getMobile()));
		}
		if (!Global.TRUE.equals(userExtendService.checkMemberMobile(oldLoginCode, memberUser.getEmail()/*, null*/))) {
			return renderResult(Global.FALSE, text("保存用户失败，登录邮箱''{0}''已存在", memberUser.getEmail()));
		}
		if (StringUtils.inString(op, Global.OP_ADD, Global.OP_EDIT)
				&& UserUtils.getSubject().isPermitted("sys:memberUser:edit")){
			memberUserService.save(memberUser);
		}
		if (StringUtils.inString(op, Global.OP_ADD, Global.OP_AUTH)
				&& UserUtils.getSubject().isPermitted("sys:memberUser:authRole")){
			userService.saveAuth(memberUser);
		}
		return renderResult(Global.TRUE, text("保存用户''{0}''成功", memberUser.getUserName()));
	}

	/**
	 * 导出用户数据
	 */
	@RequiresPermissions("sys:memberUser:view")
	@RequestMapping(value = "exportData")
	public void exportData(MemberUser memberUser, Boolean isAll, String ctrlPermi, HttpServletResponse response) {
		memberUser.getMember().getOffice().setIsQueryChildren(true);
		memberUser.getMember().getCompany().setIsQueryChildren(true);
		if (!(isAll != null && isAll) || Global.isStrictMode()){
			memberUserService.addDataScopeFilter(memberUser, ctrlPermi);
		}
		List<MemberUser> list = memberUserService.findList(memberUser);
		String fileName = "用户数据" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
		try(ExcelExport ee = new ExcelExport("用户数据", MemberUser.class)){
			ee.setDataList(list).write(response, fileName);
		}
	}

	/**
	 * 下载导入用户数据模板
	 */
	@RequiresPermissions("sys:memberUser:view")
	@RequestMapping(value = "importTemplate")
	public void importTemplate(HttpServletResponse response) {
		MemberUser memberUser = new MemberUser();
		User user = UserUtils.getUser();
		if (User.USER_TYPE_EMPLOYEE.equals(user.getUserType())){
			memberUser = memberUserService.get(user.getUserCode());
		}else{
			BeanUtils.copyProperties(user, memberUser);
		}
		List<MemberUser> list = ListUtils.newArrayList(memberUser);
		String fileName = "用户数据模板.xlsx";
		try(ExcelExport ee = new ExcelExport("用户数据", EmpUser.class, Type.IMPORT)){
			ee.setDataList(list).write(response, fileName);
		}
	}

	/**
	 * 导入用户数据
	 */
	@ResponseBody
	@RequiresPermissions("sys:memberUser:edit")
	@PostMapping(value = "importData")
	public String importData(MultipartFile file, String updateSupport) {
		try {
			boolean isUpdateSupport = Global.YES.equals(updateSupport);
			String message = memberUserService.importData(file, isUpdateSupport);
			return renderResult(Global.TRUE, "posfull:"+message);
		} catch (Exception ex) {
			return renderResult(Global.FALSE, "posfull:"+ex.getMessage());
		}
	}
	
	/**
	 * 停用用户
	 * @param memberUser
	 * @return
	 */
	@RequiresPermissions("sys:memberUser:updateStatus")
	@ResponseBody
	@RequestMapping(value = "disable")
	public String disable(MemberUser memberUser) {
		if (User.isSuperAdmin(memberUser.getUserCode())) {
			return renderResult(Global.FALSE, "非法操作，不能够操作此用户！");
		}
		if (!MemberUser.USER_TYPE_MEMBER.equals(memberUser.getUserType())){
			return renderResult(Global.FALSE, "非法操作，不能够操作此用户！");
		}
		if (memberUser.getCurrentUser().getUserCode().equals(memberUser.getUserCode())) {
			return renderResult(Global.FALSE, text("停用用户失败，不允许停用当前用户"));
		}
		memberUser.setStatus(User.STATUS_DISABLE);
		userService.updateStatus(memberUser);
		return renderResult(Global.TRUE, text("停用用户''{0}''成功", memberUser.getUserName()));
	}
	
	/**
	 * 启用用户
	 * @param memberUser
	 * @return
	 */
	@RequiresPermissions("sys:memberUser:updateStatus")
	@ResponseBody
	@RequestMapping(value = "enable")
	public String enable(MemberUser memberUser) {
		if (User.isSuperAdmin(memberUser.getUserCode())) {
			return renderResult(Global.FALSE, "非法操作，不能够操作此用户！");
		}
		if (!MemberUser.USER_TYPE_MEMBER.equals(memberUser.getUserType())){
			return renderResult(Global.FALSE, "非法操作，不能够操作此用户！");
		}
		memberUser.setStatus(User.STATUS_NORMAL);
		userService.updateStatus(memberUser);
		return renderResult(Global.TRUE, text("启用用户''{0}''成功", memberUser.getUserName()));
	}
	
	/**
	 * 密码重置
	 * @param memberUser
	 * @return
	 */
	@RequiresPermissions("sys:memberUser:resetpwd")
	@RequestMapping(value = "resetpwd")
	@ResponseBody
	public String resetpwd(MemberUser memberUser) {
		if (User.isSuperAdmin(memberUser.getUserCode())) {
			return renderResult(Global.FALSE, "非法操作，不能够操作此用户！");
		}
		if (!memberUser.USER_TYPE_MEMBER.equals(memberUser.getUserType())){
			return renderResult(Global.FALSE, "非法操作，不能够操作此用户！");
		}
		userService.updatePassword(memberUser.getUserCode(), null);
		return renderResult(Global.TRUE, text("重置用户''{0}''密码成功", memberUser.getUserName()));
	}

	/**
	 * 删除用户
	 * @param memberUser
	 * @return
	 */
	@RequiresPermissions("sys:memberUser:edit")
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(MemberUser memberUser) {
		if (User.isSuperAdmin(memberUser.getUserCode())) {
			return renderResult(Global.FALSE, "非法操作，不能够操作此用户！");
		}
		if (!MemberUser.USER_TYPE_MEMBER.equals(memberUser.getUserType())){
			return renderResult(Global.FALSE, "非法操作，不能够操作此用户！");
		}
		if (memberUser.getCurrentUser().getUserCode().equals(memberUser.getUserCode())) {
			return renderResult(Global.FALSE, text("删除用户失败，不允许删除当前用户"));
		}
		memberUserService.delete(memberUser);
		return renderResult(Global.TRUE, text("删除用户''{0}''成功", memberUser.getUserName()));
	}
	
	/** 
	 * 用户授权数据权限
	 */
	@RequiresPermissions("sys:memberUser:authDataScope")
	@RequestMapping(value = "formAuthDataScope")
	public String formAuthDataScope(MemberUser memberUser, Model model, HttpServletRequest request) {
		UserDataScope userDataScope = new UserDataScope();
		userDataScope.setUserCode(memberUser.getUserCode());
		userDataScope.setCtrlPermi(UserDataScope.CTRL_PERMI_HAVE);
		List<UserDataScope> userDataScopeList = userService.findDataScopeList(userDataScope);
		model.addAttribute("userDataScopeList", userDataScopeList);
		model.addAttribute("memberUser", memberUser);
		return "modules/kj/member/memberUserFormAuthDataScope";
	}
	
	/** 
	 * 保存用户授权数据权限
	 */
	@RequiresPermissions("sys:memberUser:authDataScope")
	@RequestMapping(value = "saveAuthDataScope")
	@ResponseBody
	public String saveAuthDataScope(MemberUser memberUser, HttpServletRequest request) {
		if (User.isSuperAdmin(memberUser.getUserCode())) {
			return renderResult(Global.FALSE, "非法操作，不能够操作此用户！");
		}
		if (!MemberUser.USER_TYPE_MEMBER.equals(memberUser.getUserType())){
			return renderResult(Global.FALSE, "非法操作，不能够操作此用户！");
		}
		memberUser.setMgrType(User.MGR_TYPE_NOT_ADMIN);
		userService.saveAuthDataScope(memberUser);
		return renderResult(Global.TRUE, text("用户分配数据权限成功"));
	}

	/**
	 * 根据机构查询用户树格式
	 * @param idPrefix id前缀，默认 u_
	 * @param pId 父级编码，默认 0
	 * @param officeCode 机构Code
	 * @param companyCode 公司Code
	 * @param postCode 岗位Code
	 * @param roleCode 角色Code
	 * @param isAll 是否显示所有用户（true：不进行权限过滤）
	 * @param isShowCode 是否显示编码（true or 1：显示在左侧；2：显示在右侧；false or null：不显示）
	 * @return
	 */
	@RequiresPermissions("user")
	@RequestMapping(value = "treeData")
	@ResponseBody
	public List<Map<String, Object>> treeData(String idPrefix, String pId,
			String officeCode, String companyCode, String postCode, String roleCode, 
			Boolean isAll, String isShowCode, String ctrlPermi) {
		List<Map<String, Object>> mapList = ListUtils.newArrayList();
		MemberUser memberUser = new MemberUser();
		Member member = memberUser.getMember();
		member.getOffice().setOfficeCode(officeCode);
		member.getOffice().setIsQueryChildren(false);
		member.getCompany().setCompanyCode(companyCode);
		member.getCompany().setIsQueryChildren(false);
		memberUser.setRoleCode(roleCode);
		memberUser.setStatus(User.STATUS_NORMAL);
		memberUser.setUserType(User.USER_TYPE_EMPLOYEE);
		if (!(isAll != null && isAll) || Global.isStrictMode()) {
			memberUserService.addDataScopeFilter(memberUser, ctrlPermi);
		}
		List<MemberUser> list = memberUserService.findList(memberUser);
		for (int i = 0; i < list.size(); i++) {
			MemberUser e = list.get(i);
			Map<String, Object> map = MapUtils.newHashMap();
			map.put("id", StringUtils.defaultIfBlank(idPrefix, "u_") + e.getId());
			map.put("pId", StringUtils.defaultIfBlank(pId, "0"));
			map.put("name", StringUtils.getTreeNodeName(isShowCode, e.getLoginCode(), e.getUserName()));
			mapList.add(map);
		}
		return mapList;
	}
	
	/**
	 * 选择员工对话框
	 */
	@RequiresPermissions("user")
	@RequestMapping(value = "memberUserSelect")
	public String memberUserSelect(MemberUser memberUser, String selectData, Model model) {
		String selectDataJson = EncodeUtils.decodeUrl(selectData);
		if (JsonMapper.fromJson(selectDataJson, Map.class) != null){
			model.addAttribute("selectData", selectDataJson);
		}
		model.addAttribute("memberUser", memberUser);
		return "modules/kj/member/memberUserSelect";
	}
	
}
